import { _decorator, Component, Node ,director, log, AudioClip, Label, find, sys, CCObjectFlags, Prefab, instantiate, Color, resources, game } from 'cc';
import { dogC1 } from './dogC1';
import { dogC2 } from './dogC2';
import { duckC } from './duckC';
import { AudioManager } from './AudioManager';


const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    // 静态实例，确保全局唯一
    private static _instance: GameManager = null;
    // 游戏是否结束标志，0是表示未开始，1 表示狗 ,2 表示进行中，3 表示结束
    public GameStatus: number = 0;
    // 难度
    public difficulty: number = 1;
    // 创建一个定时器，用于控制 spawnDog 的调用间隔
    private spawnInterval: number = 3;

    //是否随机变化位置
    public isRandom: number = 0;

    //初始化数量
    private _counter: number = 0;
    //死亡数量
    private _deadNum: number = 0;
    private _score: number = 0;
    @property
    public max_count:number = 20;

    @property(dogC1)
    private dogC1Ref: dogC1 | null = null;
    
    @property(dogC2)
    private dogC2Ref: dogC2 | null = null;

    @property({ type: Prefab })
    duckPrefab: Prefab | null = null; // 👈 在编辑器中拖入 Dog.prefab
    

    // 单例访问器
    public static get instance(): GameManager {
        return this._instance;
    }
    
    onLoad() {
        if (GameManager._instance === null) {
            GameManager._instance = this;
            director.addPersistRootNode(this.node);
        } else {
            // 如果已存在实例，销毁当前节点
            this.node.destroy();
        }
    }
    
    start() {
        console.log("GameManager初始化完成");
        this.initGame();
    }
    // 退出游戏
    public exitGame() {
        log("exitGame");
        if (sys.isNative) {
            // 退出游戏
            game.end();
            // director.end();
        } else {
            // 退出游戏
            window.history.back();
        }
    }
    /**
     * 初始化游戏
     */
    public initGame() {

        let fenNode = find("Canvas/fen");
        fenNode.getComponent(Label).string = '记分板：共 '+ this.max_count +' 只鸭子，打掉 0 只 ，跑掉 0 只 。'
       
        this._counter = 0;
        this._deadNum = 0;
        this._score = 0;

        this.GameStatus = 0;
        let nodeEnd = find("Canvas/end");
        nodeEnd.active = false;
        let nodeStart = find("Canvas/start");
        nodeStart.active = true;
    }

    public paying(event: Event, customEventData: string) {
        log("paying",event,customEventData);
        this.difficulty = parseInt(customEventData);
        if(this.difficulty == 1){
            this.spawnInterval = 3;
            this.max_count=15
        }else if(this.difficulty == 2){
            this.spawnInterval = 1;
            this.max_count=20;
        }else if(this.difficulty == 3){
            this.spawnInterval = 0.8;
            this.max_count=25
            this.isRandom = 1;
        }

        let fenNode = find("Canvas/fen");
        fenNode.getComponent(Label).string = '记分板：共 '+ this.max_count +' 只鸭子，打掉 0 只 ，跑掉 0 只 。'

        this.GameStatus = 1;
        let nodeEnd = find("Canvas/end");
        nodeEnd.active = false;
        let nodeStart = find("Canvas/start");
        nodeStart.active = false;
        this.dogC1Ref?.initDog(); 
    }

    public duckDead(isZhong:number,x:number) {
        log("duckDead",isZhong); //是否打中枪
        this._deadNum++;
        log("this._deadNum",this._deadNum);
        let dogComp2 = find("Canvas/main/dog2").getComponent(dogC2);
        if(isZhong == 10){ //打中
            this._score++;
             AudioManager.instance.playSFX('sound/dog_jiao', false);
            dogComp2.yingDog(x);
        }else{ //没打中
            AudioManager.instance.playSFX('sound/dog-laugh', false,0.5);
            dogComp2.shuDog(x);
        }

         let fenNode = find("Canvas/fen");
         fenNode.getComponent(Label).string = '记分板：共 '+ this.max_count +' 只鸭子，打掉 '+ this._score +' 只 ，跑掉 '+ (this._deadNum - this._score) +' 只 。'

        if (this._deadNum >= this.max_count) {
            this.initEnd();
        }
    }

    public paying2() {
        this.schedule(this.spawnDuck, this.spawnInterval);
    }
    private spawnDuck() { 
        this._counter++;
        if (this._counter >= this.max_count) {
            this.unschedule(this.spawnDuck); 
        }
        let nodeDuck = find("Canvas/ducks");
        const duckNode = instantiate(this.duckPrefab);
        nodeDuck.addChild(duckNode);
        const duckComp = duckNode.getComponent(duckC);
        const options = ["flyL", "flyR", "flyTL","flyTR"];
        const randomChoice = options[Math.floor(Math.random() * options.length)];
        duckComp.toFly(randomChoice,this.isRandom);
    }


    public initEnd() {
        this.GameStatus = 3;
        let nodeEnd = find("Canvas/end");
        nodeEnd.active = true;
        let targetLabel = nodeEnd.getChildByName('label1').getComponent(Label)
        if(this._score >= this.max_count * 0.9){
            targetLabel.string = '你 赢 了'
            targetLabel.color =  new Color(0, 255,0, 255);
        }else{
            targetLabel.string = '你 输 了'
            targetLabel.color =  new Color(255, 0,0, 255);
        }
        
        nodeEnd.getChildByName('label2').getComponent(Label).string = '游戏结束，得分：'+ this._score +' 只 ，跑掉 '+ (this._deadNum - this._score) +' 只 。'



        let nodeStart = find("Canvas/start");
        nodeStart.active = false;
        this.unscheduleAllCallbacks();
    }
    
}


